//////////////////////////////////////////////////////////////////////////////////
//	File Name:	ObjectManager.cpp
//	Author	 :	Yuri Oyoko
//	Purpose	 :	The object manager handles the rendering and updating of all
//				objects currently in the game
//////////////////////////////////////////////////////////////////////////////////

//Includes
#include "ObjectManager.h"
#include "BaseObject.h"

ObjectManager* ObjectManager::Instance = NULL;

ObjectManager::ObjectManager()
{
}
ObjectManager::~ObjectManager()
{
}
ObjectManager* ObjectManager::GetInstance()
{
	if(!Instance)
	{
		Instance = new ObjectManager;
	}
	return Instance;
}
void ObjectManager::DeleteInstance()
{
	if(Instance)
	{
		delete Instance;
		Instance = NULL;
	}
}
void ObjectManager::UpdateObjects(float ElapsedTime)
{
	vector<BaseObject*>::iterator theIterator = ObjectList.begin();
	vector<BaseObject*> InactiveObjects;
	while(theIterator != ObjectList.end())
	{
		if((*theIterator)->GetIsActive())
		{
			(*theIterator)->Update(ElapsedTime);
		}
		else
		{
			InactiveObjects.push_back(*theIterator);
		}
		theIterator++;
	}
	for(unsigned int i = 0; i < InactiveObjects.size(); i++)
	{
		RemoveObject(InactiveObjects[i]);
	}
	InactiveObjects.clear();
}
void ObjectManager::RenderObjects()
{
	for(unsigned int i = 0; i < ObjectList.size(); i++)
	{
		ObjectList[i]->Render();
	}
}
void ObjectManager::AddObject(BaseObject *theObject)
{
	if(theObject == NULL)
		return;
	ObjectList.push_back(theObject);
	theObject->AddReference();
}
void ObjectManager::RemoveObject(BaseObject *theObject)
{
	if(theObject == NULL)
		return;

	for(vector<BaseObject*>::iterator theIterator = ObjectList.begin(); theIterator!= ObjectList.end(); theIterator++)
	{
		if((*theIterator) == theObject)
		{
			(*theIterator)->Release();
			theIterator = ObjectList.erase(theIterator);
			break;
		}
	}

}
void ObjectManager::RemoveAllObjects()
{
	for(unsigned int i = 0; i < ObjectList.size(); i++)
	{
		ObjectList[i]->Release();
	}
	ObjectList.clear();
	
}
void ObjectManager::CheckObjectCollisions()
{
	for(unsigned int i = 0; i < ObjectList.size(); i++)
	{
		for(unsigned int j = 0; j < ObjectList.size(); j++)
		{
			if(ObjectList[i]->GetObjectType() != ObjectList[j]->GetObjectType())
			{
				if(ObjectList[i]->CheckCollision(ObjectList[j]))
				{
					break;
				}
			}
		}
	}
}